package com.kyub.test.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.validation.BindingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;

import com.kyub.test.model.Pet;
import com.kyub.test.model.MockPersonDao;
import com.kyub.test.model.Person;
import com.kyub.spring.gears.model.PojoRegistry;
import com.kyub.spring.gears.model.PojoDescriptor;
import com.kyub.spring.gears.introspect.PojoDescriptorFactory;
import com.kyub.spring.gears.vo.NavigableCollection;
import com.kyub.spring.gears.web.PropertyEditorBuilder;
import com.kyub.spring.gears.web.ControllerHelper;
import com.kyub.spring.gears.web.CrudController;

import javax.naming.ConfigurationException;

/**
 */
@Controller
public class PetController {
    private static final ArrayList volatiles = new ArrayList();

    @Autowired
    private ControllerHelper helper;

    private static final List owners = new MockPersonDao().list();

    @RequestMapping(value = "/pet/contestualAdd")
    public ModelAndView contestualAdd(@ModelAttribute(CrudController.COMMAND_POJO_NAME)Pet pojoInstance, BindingResult bindingResult) throws ConfigurationException {


        ModelAndView model = helper.buildModelAndView(new Pet());

        if (bindingResult.hasErrors()) {
            model.addObject(CrudController.COMMAND_POJO_NAME, pojoInstance);
        }
        else if(pojoInstance != null){
            volatiles.add(pojoInstance);
        }

        model.setViewName("custom/composed");

        model.addObject("pojoList", new NavigableCollection(volatiles,1,20 ));   //TODO WHAT IF I HAVE MUTILPLE TABLES??

        helper.addRelated(model,"owner",owners);
        return model;

    }

     @InitBinder
    public void initBinder(WebDataBinder binder) {

         SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));

         try {
              helper.addGearsBinder(binder,Person.class,new MockPersonDao());
          } catch (ConfigurationException e) {
             e.printStackTrace();
         }

     }



}
